package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private MongoTemplate template;
    @Autowired
    private TravelRepository repository ;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService ;
    @Override
    public void save(Travel travel) {
        travel.setId(null);
        repository.save(travel);
    }

    @Override
    public void update(Travel travel) {
        repository.save(travel);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }


    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();

       if(qo.getState()==1){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }else if(qo.getState()==-1){
           query.addCriteria(Criteria.where("state").is(Travel.STATE_REJECT));
       }

       if(StringUtils.hasLength(qo.getDestId())){
           query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
       }
        Pageable pageable = null ;
        if(qo.getOrderType()==1){
             pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.DESC, "releaseTime");
        }else if(qo.getOrderType()==2){
            pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        }else {
             pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "id");
        }

        TravelCondition day =qo.getDay();
        if(day!=null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        TravelCondition expend = qo.getExpend();
        if(expend!=null){
            query.addCriteria(Criteria.where("perExpend").gte(expend.getMin()).lte(expend.getMax()));
        }
        //条件下总数量
        long count = template.count(query, Travel.class);
        if(count==0){
            return Page.empty();
        }
        if(count<=qo.getPageSize()){
            qo.setCurrentPage(1);
        }
        query.with(pageable);

        List<Travel> travels = template.find(query, Travel.class);
        for (Travel travel : travels) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return new PageImpl<>(travels,pageable , count);
    }

    @Override
    public void changeState(String id, int state) {
        Travel travel = this.get(id);
        if(travel==null || travel.getState()==state){
            throw new LogicException("参数异常");
        }else {
            travel.setState(state);
            travel.setReleaseTime(new Date());
            travel.setLastUpdateTime(new Date());
            this.update(travel);
        }
    }

    @Override
    public String getContentById(String id) {
        String content = this.get(id).getContent();
        return content;
    }

    @Override
    public Travel get(String id) {
        if (!StringUtils.hasLength(id)) {
            return null;
        }
        Optional<Travel> op = repository.findById(id);
        if (op.isPresent()) {
            Travel travel = op.get();
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
            return travel;
        }
        return null;
    }


    @Override
    public List<Strategy> queryViewnumTop3(String destId) {
        Pageable pageable = PageRequest.of(0,3 , Sort.Direction.DESC ,"viewnum");
        List<Strategy> strategies = repository.findByDestId(destId,pageable);
        return strategies;
    }

    @Override
    public String saveOrUpdate(Travel travel) {
        if (StringUtils.hasLength(travel.getId())) {
            Travel travel1 = this.get(travel.getId());
            travel.setDestName(destinationService.get(travel.getDestId()).getName());
            travel.setLastUpdateTime(new Date());
            travel.setCreateTime(travel1.getCreateTime());
            travel.setReleaseTime(travel1.getReleaseTime());
            travel.setFavornum(travel1.getFavornum());
            travel.setSharenum(travel1.getSharenum());
            travel.setReplynum(travel1.getReplynum());
            travel.setThumbsupnum(travel1.getThumbsupnum());
            travel.setViewnum(travel1.getViewnum());
              this.update(travel);
        } else {
            //目的地名称
            travel.setDestName(destinationService.get(travel.getDestId()).getName());
            //创建时间
            travel.setCreateTime(new Date());
            //发布时间
            //最后更新时间
            travel.setLastUpdateTime(new Date());
            this.save(travel);
        }
        return travel.getId();
    }

    @Override
    public List<Travel> findByDestName(String keyword) {
        List<Travel> travels = repository.findByDestName(keyword);
        for (Travel travel : travels) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return travels;
    }
}
